<template>
  <el-dialog
    v-model="dialogVisible"
    title="关联部门"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="department-dialog">
      <!-- 已关联部门列表 -->
      <div class="existing-departments">
        <h3>已关联部门</h3>
        <el-table
          :data="existingDepartments"
          :columns="columns"
          border
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column prop="departmentName" label="部门名称" min-width="150" show-overflow-tooltip align="left" />
          <el-table-column prop="salesName" label="销售负责人" width="120" align="center" />
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加新部门 -->
      <div class="add-department">
        <h3>添加部门</h3>
        <div class="department-select">
          <el-form :model="form" label-width="100px">
            <el-form-item label="选择部门">
              <el-select
                v-model="selectedDepartment"
                style="width: 100%"
                placeholder="请选择部门"
                @change="handleDepartmentChange"
              >
                <el-option
                  v-for="dept in departmentOptions"
                  :key="dept.id"
                  :label="dept.fullPath || dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 部门用户列表 -->
        <div v-if="selectedDepartment" class="department-users">
          <h4>选择销售</h4>
          <el-form :model="form" label-width="100px">
            <el-form-item label="选择销售">
              <el-select
                v-model="selectedSales"
                style="width: 100%"
                placeholder="请选择销售"
              >
                <el-option 
                  v-for="user in departmentUsers" 
                  :key="user.id" 
                  :label="user.realName"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleAddDepartment">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { getAllDepartments } from '@/api/customer';
import { addCustomerDepartment, deleteCustomerDepartment, getCustomerDepartments } from '@/api/customer';
import axios from 'axios';

interface Department {
  id: number;
  name: string;
  parent?: Department;
  fullPath?: string;
}

interface User {
  id: number;
  username: string;
  realName: string;
  roles: Array<{ name: string }>;
}

interface FormState {
  departmentId?: number;
  userId?: number;
}

const props = defineProps<{
  customerId: number;
  visible: boolean;
}>();

const emit = defineEmits(['update:visible']);

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const departmentOptions = ref<Department[]>([]);
const selectedDepartment = ref<number>();
const selectedSales = ref<number | undefined>();
const departmentUsers = ref<User[]>([]);
const existingDepartments = ref<any[]>([]);
const form = reactive<FormState>({
  departmentId: undefined,
  userId: undefined
});

// 表格列定义
const columns = [
  {
    title: '部门名称',
    dataIndex: 'departmentName',
    key: 'departmentName',
  },
  {
    title: '销售',
    dataIndex: 'salesName',
    key: 'salesName',
  },
  {
    title: '操作',
    key: 'action',
  },
];

// 加载部门列表
const loadDepartments = async () => {
  console.log('开始加载部门列表');
  try {
    const response = await getAllDepartments();
    console.log('获取到的部门列表:', response.data);
    departmentOptions.value = response.data;
  } catch (error) {
    console.error('加载部门列表失败:', error);
    ElMessage.error('加载部门列表失败');
  }
};

// 加载部门用户
const loadDepartmentUsers = async (departmentId: number) => {
  console.log('开始加载部门用户，部门ID:', departmentId);
  try {
    const response = await axios.get(`/api/departments/${departmentId}/users`);
    console.log('获取到的部门用户列表:', response.data);
    departmentUsers.value = response.data;
  } catch (error) {
    console.error('加载部门用户失败:', error);
    ElMessage.error('加载部门用户失败');
  }
};

// 加载已关联部门
const loadExistingDepartments = async () => {
  try {
    console.log('开始加载已关联部门，客户ID:', props.customerId);
    const response = await getCustomerDepartments(props.customerId);
    console.log('已关联部门数据:', response.data);
    existingDepartments.value = response.data;
  } catch (error) {
    console.error('加载已关联部门失败:', error);
    ElMessage.error('加载已关联部门失败');
  }
};

// 处理部门选择变化
const handleDepartmentChange = async (value: number) => {
  console.log('部门选择变化，选中的部门ID:', value);
  console.log('当前部门选项:', departmentOptions.value);
  selectedDepartment.value = value;
  await loadDepartmentUsers(value);
};

// 处理删除
const handleDelete = async (record: any) => {
  try {
    await deleteCustomerDepartment(props.customerId, record.departmentId);
    ElMessage.success('删除成功');
    await loadExistingDepartments();
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error('删除失败');
  }
};

// 添加部门关联
const handleAddDepartment = async () => {
  if (!selectedDepartment.value || !selectedSales.value) {
    ElMessage.error('请选择部门和销售');
    return;
  }
  
  try {
    await addCustomerDepartment({
      customerId: props.customerId,
      departmentId: selectedDepartment.value,
      salesId: selectedSales.value
    });
    ElMessage.success('添加成功');
    selectedDepartment.value = undefined;
    selectedSales.value = undefined;
    loadExistingDepartments();
  } catch (error) {
    console.error('添加部门关联失败:', error);
    ElMessage.error('添加部门关联失败');
  }
};

// 处理对话框关闭
const handleClose = () => {
  dialogVisible.value = false;
  // 清空表单
  form.departmentId = undefined;
  form.userId = undefined;
};

// 监听visible属性变化
watch(() => props.visible, (newVal) => {
  console.log('visible属性变化:', newVal);
  if (newVal) {
    console.log('对话框显示，开始加载数据');
    // 每次显示对话框时重新加载数据
    loadDepartments().then(() => {
      console.log('部门列表加载完成');
      return loadExistingDepartments();
    }).then(() => {
      console.log('已关联部门加载完成');
    }).catch(error => {
      console.error('加载数据失败:', error);
      ElMessage.error('加载数据失败');
    });
  }
}, { immediate: true });
</script>

<style scoped>
.department-dialog {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.existing-departments {
  margin-bottom: 20px;
}

.add-department {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.department-select {
  margin-bottom: 20px;
}

.department-users {
  margin-top: 20px;
}

h3 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
}

h4 {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
}
</style> 